<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>canvas实现图片前端js压缩</title>
    <style>
        *{margin: 0;padding: 0;}
        body{font-size: 16px;padding: 40px 30px;}
        /* 自定义按钮 */
        .m-btn{
            display: inline-block;
            padding: 7px 9px;
            font-size: 12px;
            cursor: pointer;
            user-select:none;
            -webkit-user-select:none;
            -moz-user-select:none;
            -ms-user-select:none;
            -webkit-touch-callout:none;
            border-radius: 4px;
            color: #fff;
            background-color: #20a0ff;
            border-color: #20a0ff;
        }
        .m-btn:hover{
            background: #4db3ff;
            border-color: #4db3ff;
        }
        .m-btn:active{
            background: #1d90e6;
            border-color: #1d90e6;
        }

        /* 压缩结果 */
        .zip_result{

        }
    </style>
</head>
<body>
    <h3 style="text-align: center;font-size: 30px;">canvas图片压缩</h3>
    <label class="m-btn">
        <input id="upload" type="file" accept="image/gif,image/jpeg,image/png,image/svg" multiple style="display: none;">
        点击上传
    </label>
    <div id="zip_result">

    </div>
    <script>
        var eleFile = document.querySelector('#upload');

        // 压缩图片需要的一些元素和对象
        var reader = new FileReader(), img = new Image();

        // 选择的文件对象
        var file = null;

        // 缩放图片需要的canvas
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');

        eleFile.addEventListener('change', function (event) {
            file = event.target.files[0];
            reader.readAsDataURL(file);
        })

        reader.onload = function (e) {
            img.src = e.target.result;
        }

        img.onload = function () {
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;

            // 最大尺寸限制
            var maxWidth = 400, maxHeight = 400;

            // 目标的实际尺寸
            var targetWidth = 0, targetHeight = 0;

            if(originWidth > maxWidth || originHeight > maxHeight){
                if(originWidth / originHeight > maxWidth / maxHeight){
                    // 如果图片更宽
                    targetWidth =  maxWidth;
                    targetHeight = maxWidth / originWidth * originHeight;
                }else {
                    targetHeight = maxHeight;
                    targetWidth = maxHeight / originHeight * originWidth;
                }
            }

            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            context.clearRect(0,0,targetWidth,targetHeight);
            // 图片压缩
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            // canvas转为blob并上传
            canvas.toBlob(function (blob) {
                // 图片ajax上传
                var xhr = new XMLHttpRequest();

                // 文件上传成功
                xhr.onreadystatechange = function () {
                    if(xhr.status === 200){
                        // xhr.responseText 就是返回的数据
                        console.log('图片上传成功');
                    }
                }
                // 文件上传中
                xhr.upload.onprogress = function (e) {
                    console.log('正在上传',e);
                    var percent = parseInt(e.loaded / e.total * 100);
                }
                // 文件上传错误
                xhr.upload.onerror = function () {
                    console.log('文件上传失败');
                }
                // 开始上传
                xhr.open('POST','',true);
                xhr.send(blob);
            },file.type || 'image/png');
        }

    </script>
</body>
</html>